package com.shengchang.hu.supervision.Utils;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;


public class PubFunction {
    public static String BaseSaveDir= Environment.getExternalStorageDirectory()+"/touchscale";

    public static final String DBName="records.db";
    public static final String WlanDBName="Wlanrecords.db";
    public static final String PREFS_NAME = "ScaleSet";

    public static final int GFSF_ZF=(0x01<<0);		//空格用0
    public static final int GFSF_PLUS=(0x01<<1);	//前方带有负号
    public static final int GFSF_SPACE=(0x01<<2);	//如果值为正,则即使加了0,
    public static final int GFSF_CF=(0x01<<3);	//前方带有%C
    public static final int GFSF_SF=(0x01<<4);	//前方带有%s
    public static final int GFSF_ST=(0x01<<5);	//十六进制
    public static final int GFSF_ALLSIGN=(0x01<<6);
    public static final int	DEFUALTLISTHEIGHT=40;
    public static String GetExpShowFormatPub(int exp, int len, int Flag)
    {
        StringBuilder stringBuilder=new StringBuilder();
        if((Flag&GFSF_PLUS)>0)
        {
            stringBuilder.append('-');
            len--;
        }
        if((Flag&GFSF_CF)>0)
        {
            stringBuilder.append('%');
            stringBuilder.append('c');
        }
        if((Flag&GFSF_SF)>0)
        {
            stringBuilder.append('%');
            stringBuilder.append('s');
        }

        stringBuilder.append('%');
        if((Flag&GFSF_SPACE)>0)
        {
            stringBuilder.append(' ');
        }
        if((Flag&GFSF_ALLSIGN)>0)
        {
            stringBuilder.append('+');
        }
        if((Flag&GFSF_ZF)>0)
        {
            stringBuilder.append('0');
        }
        if((Flag&GFSF_ST)>0)
        {
            if(exp==0)stringBuilder.append((char)(len+'0'));
            else
            {
                char  len1=(char) (len-exp-2);
                if(exp>1)len1-=1;
                if(len1<1)len1=1;
                if(len1>9)
                {
                    stringBuilder.append('1');
                    stringBuilder.append((char)(len1-10+'0'));
                }
                else {
                    stringBuilder.append((char)(len1+'0'));
                }
            }
            stringBuilder.append('d');
            if(exp>0)
            {
                stringBuilder.append('.');
                stringBuilder.append('%');
                if(exp==1)stringBuilder.append('2');
                else stringBuilder.append((char)(exp+'2'));
                stringBuilder.append('.');
                stringBuilder.append((char)(exp-1+'0'));
                stringBuilder.append('f');
            }
        }
        else
        {
            if(len<0)len=0;
            if(len>9)
            {
                stringBuilder.append('1');
                stringBuilder.append((char)(len-10+'0'));
            }
            else {
                stringBuilder.append((char)(len+'0'));
            }
            stringBuilder.append('.');
            stringBuilder.append((char)(exp+'0'));
            stringBuilder.append('f');
        }
        return stringBuilder.toString();
    }
    public static String GetFloatShowFormatPub(float flo, int len, int Flag)
    {
        if((Flag&GFSF_ST)>0)return GetExpShowFormatPub(ExpToShowExpU2(GetFloatExp(flo)),len,Flag);
        else return GetExpShowFormatPub(ExpToShowExp(GetFloatExp(flo)),len,Flag);
    }
    /**************************************************************************
     *      函数原型char GetFloatExp(float flo)
     *      �?   能：取得浮点数十进制格式的指数，�?的指数为0
     *				0.1的指数为�?�?0的指数为1,0的指数为-128
     **************************************************************************/
    public static int GetFloatExp(float flo)
    {
        int  Dot=0;
        flo= Math.abs(flo);
        if(flo>=0.99)
        {
            while(flo>=9.9) {flo/=10;Dot++;}
            return Dot;
        }
        else if(flo>=0.00000001)
        {
            while(flo<0.99) {flo*=10;Dot--;}
            return Dot;
        }
        else return -9;
    }
    public static int  GetFloatDig(float flo)
    {
        int i;
        flo=flo-(long)flo;
        for(i=0;i<10;i++)
        {
            if(flo==(long)flo)break;
            flo=flo*10;
        }
        return i;
    }
    public static int ExpToShowExp(int exp)
    {
        if(exp>0)exp=0;
        if(Math.abs(exp)>=8)exp=7;
        return Math.abs(exp);
    }
    public static int ExpToShowExpU2(int exp)
    {
        if(exp>0)return 0;
        if(Math.abs(exp)>=8)exp=7;
        return Math.abs(exp)+1;
    }
    public static float GetFormatDiv(float fdiv)
    {
        int exp;
        exp=GetFloatExp(fdiv);
        fdiv=(float) (fdiv/ Math.pow(10,exp));
        if(fdiv>7.5)fdiv=10;
        else if(fdiv>3.5)fdiv=5;
        else if(fdiv>1.5)fdiv=2;
        else fdiv=1;
        fdiv*= Math.pow(10,exp);
        return fdiv;
    }

    static float U2DivTab[][]={
            {12000,16000},
            {5600,8000},
            {2400,3200},
            {1200,1600},
            {560,800},
            {240,320},
            {120,160},
            {56,80},
            {24,32},
            {12,16},
            {6,8},
            {3,4},
            {(float) 1.5,2},
            {(float) 0.75,1},
    };
    public static float GetU2FormatDiv(float fdiv)
    {
        if(fdiv<0.75)
        {
            return GetFormatDiv(fdiv);
        }
        else
        {
            for(int i=0;i<U2DivTab.length/2;i++)
            {
                if(fdiv>=U2DivTab[i][0])
                {
                    fdiv=U2DivTab[i][1];
                    break;
                }
            }
            return fdiv;
        }

    }
    public static  byte ASCII2Bin(byte strdata)
    {
        if((strdata<='9')&&(strdata>='0'))return (byte) (strdata-'0');
        else if((strdata<='z')&&(strdata>='a'))return (byte) (strdata-'a'+10);
        else return (byte) (strdata-'A'+10);
    }
    public static  char ASCII2Bin(char strdata)
    {
        if((strdata<='9')&&(strdata>='0'))return (char) (strdata-'0');
        else if((strdata<='z')&&(strdata>='a'))return (char) (strdata-'a'+10);
        else return (char) (strdata-'A'+10);
    }
    public static  void Bin2Bin(byte ascii,byte bin[])
    {
        bin[0]=(byte) ((ascii>>4)&0xf);
        bin[0]+=bin[0]<10?'0':0x37;
        bin[1]=(byte) (ascii&0xf);
        bin[1]+=bin[1]<10?'0':0x37;
    }

    public static int PowMod(int base, int pow, int n)
    {
        int    a=base, b=pow, c=1;
        while(b!=0)
        {
            while((b & 1)==0)
            {
                b>>=1;  //a=a * a % n;    //函数看起来可以处�?4位的整数，但由于这里a*a在a>=2^32时已经�?成了溢出，因此实际处理范围没�?4�?
                a=(int) ((long)a*a%n);
            }
            b--;        //c=a * c % n;        //这里也会溢出，若�?4位整数拆为两�?2位整数不知是否可以解决这个问题�?
            c=(int) ((long)a*c%n);
        }
        return c;
    }

    public static int getTextWidth(Paint paint, String str) {
        // TODO Auto-generated method stub
        int iRet = 0;
        if (str != null && str.length() > 0) {
            int len = str.length();
            float[] widths = new float[len];
            paint.getTextWidths(str, widths);
            for (int j = 0; j < len; j++) {
                iRet += (int) Math.ceil(widths[j]);
            }
        }
        return iRet;
    }

    //读文�?
    public static String readSDFile(String fileName) {

        String res=null;
        try {
            File file = new File(fileName);
            long length = file.length();
            FileReader fis;

            fis = new FileReader(file);

            char[] bufer=new char[(int) length];
            fis.read(bufer);
            fis.close();
            res=new String(bufer);
        }
        catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return res;
    }

    public static byte[] readSDBinFile(String fileName)  {

        byte[] buffer=null;
        try {
            File file = new File(fileName);
            FileInputStream fis = new FileInputStream(file);

            int length = fis.available();

            buffer = new byte[length];
            fis.read(buffer);
            fis.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return buffer;
    }
    //读文件
//	public static String readSDFile_UTF8(String fileName) throws IOException {
//
//	        File file = new File(fileName);
//
//	        FileInputStream fis = new FileInputStream(file);
//
//	        int length = fis.available();
//
//	         byte [] buffer = new byte[length];
//	         fis.read(buffer);
//
//	         String res = EncodingUtils.getString(buffer, "UTF-8");
//
//	         fis.close();
//	         return res;
//	}
    public static String readSDFile_Auto(String fileName, String defaultEnc )
    {
        try {
            return _readSDFile_Auto(fileName,defaultEnc);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    public static String readSDFile_Auto_GBK(String fileName )
    {
        try {
            return _readSDFile_Auto(fileName,"GBK");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    public static String _readSDFile_Auto(String fileName, String defaultEnc ) throws IOException {

        File file = new File(fileName);

        FileInputStream fis = new FileInputStream(file);

        int length = fis.available();

        byte  buffer[] = new byte[length];
        fis.read(buffer);
        String encoding;

        int  unread;

        if ( (length>3)&&(buffer[0] == (byte)0x00) && (buffer[1] == (byte)0x00) &&
                (buffer[2] == (byte)0xFE) && (buffer[3] == (byte)0xFF) ) {
            encoding = "UTF-32BE";
            unread = 4;
        } else if ( (length>3)&&(buffer[0] == (byte)0xFF) && (buffer[1] == (byte)0xFE) &&
                (buffer[2] == (byte)0x00) && (buffer[3] == (byte)0x00) ) {
            encoding = "UTF-32LE";
            unread = 4;
        } else if (  (length>2)&&(buffer[0] == (byte)0xEF) && (buffer[1] == (byte)0xBB) &&
                (buffer[2] == (byte)0xBF) ) {
            encoding = "UTF-8";
            unread = 3;
        } else if ( (length>1)&&(buffer[0] == (byte)0xFE) && (buffer[1] == (byte)0xFF) ) {
            encoding = "UTF-16BE";
            unread =  2;
        } else if ( (length>1)&&(buffer[0] == (byte)0xFF) && (buffer[1] == (byte)0xFE) ) {
            encoding = "UTF-16LE";
            unread = 2;
        } else {
            // Unicode BOM mark not found, unread all bytes
            encoding = defaultEnc;
            unread = 0;
        }
        //Log.d("ReadSdFileAuto", String.valueOf(unread));
        byte  nbuffer[] = new byte[length-unread];
        for(int i=0;i<length-unread;i++)nbuffer[i]=buffer[i+unread];
        String res = new String(nbuffer, encoding);   	//这个函数不会自动去除bom

        fis.close();
        return res;
    }
    //写文�?
    public static void writeSDFile_UTF8(String fileName, String write_str) throws IOException {

        File file = new File(fileName);
        if (!file.exists())     file.createNewFile();//建立文件

        FileOutputStream fos = new FileOutputStream(file);
        if (file.length() < 1) {

            final byte[] bom = new byte[] { (byte)0xEF, (byte)0xBB, (byte)0xBF };

            fos.write(bom);

        }
        OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
        osw.write(write_str);
        osw.flush();
        osw.close();
    }
    public static void writeSDFile(String fileName, String write_str) throws IOException {

        File file = new File(fileName);
        if (!file.exists())     file.createNewFile();//建立文件


        FileWriter fw = new FileWriter(file);
        fw.write(write_str);
        fw.flush();
        if (fw != null) fw.close();
    }

    public static boolean IsCanUseSdCard() {
        try {
            return Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    public static String savePicToSdcard(Bitmap bitmap, String path,
                                         String fileName) {
        File exportDir = new File(path);
        if (!exportDir.exists()) {
            exportDir.mkdirs();
        }
        if (bitmap == null) {
            return fileName;
        } else {
            File destFile = new File(path,fileName);

            OutputStream os = null;
            try {
                if (!destFile.exists())  destFile.createNewFile();//建立文件
                os = new FileOutputStream(destFile);
                bitmap.compress(CompressFormat.JPEG, 100, os);
                os.flush();
                os.close();
            } catch (IOException e) {
            }
        }
        return fileName;
    }
    /**
     2  * 5、创建目录
     3  */
    public static boolean Backup_Restore_db(Context ctx, String file, boolean Backup)
    {
        // TODO Auto-generated method stub
        File dbFile = ctx.getDatabasePath(file);  // 获得数据库路径，默认是/data/data/(包名)org.dlion/databases/
        File exportDir = new File(BaseSaveDir+"/backfile");
        if (!exportDir.exists()) {
            exportDir.mkdirs();
        }
        File backup = new File(exportDir, dbFile.getName());
        if (Backup) {
            try {
                backup.createNewFile();
                fileCopy(dbFile, backup);
                return true;
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
                return false;
            }
        } else {
            try {
                fileCopy(backup, dbFile);
                return true;
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
                return false;
            }
        }
    }
    @SuppressLint({ "ShowToast", "SdCardPath" })
    public static boolean Backup_Restore_Setting(Context ctx, String name, boolean Backup)
    {
        // TODO Auto-generated method stub
        ctx=ctx.getApplicationContext();
        File dbFile = new File("/data/data/"+ctx.getPackageName()+"/shared_prefs",name); // 获得数据库路径，默认是/data/data/(包名)org.dlion/databases/
        File exportDir = new File(BaseSaveDir+"/backfile");
        Toast.makeText(ctx, dbFile.toString(), Toast.LENGTH_SHORT);
        if (!exportDir.exists()) {
            exportDir.mkdirs();
        }
        File backup = new File(exportDir, dbFile.getName());
        if (Backup) {
            try {
                backup.createNewFile();
                fileCopy(dbFile, backup);
                return true;
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
                return false;
            }
        } else {
            try {
                fileCopy(backup, dbFile);
                return true;
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
                return false;
            }
        }
    }
    private static void fileCopy(File dbFile, File backup) throws IOException {
        // TODO Auto-generated method stub
        @SuppressWarnings("resource")
        FileChannel inChannel = new FileInputStream(dbFile).getChannel();
        @SuppressWarnings("resource")
        FileChannel outChannel = new FileOutputStream(backup).getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (inChannel != null) {
                inChannel.close();
            }
            if (outChannel != null) {
                outChannel.close();
            }
        }
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static String getSuffix(String filename){
        int dix = filename.lastIndexOf('.');
        if(dix<0){
            return "";
        }
        else{
            return filename.substring(dix+1);
        }
    }
    public static int CSC2StringBuf(String csvString, String buf[][], int maxwidthn, int maxlen)
    {
        int n=0;
        String onelineString[];
        int dix = csvString.indexOf("\r\n");
        if(dix<0)
        {
            dix=csvString.indexOf("\r");
            if(dix<0)
            {
                dix=csvString.indexOf("\n");
                if(dix<0)return 0;
                else onelineString=csvString.split("\n",maxlen);
            }
            else {
                onelineString=csvString.split("\r",maxlen);
            }
        }
        else {
            onelineString=csvString.split("\r\n",maxlen);
        }
        for(n=0;n<onelineString.length;n++)
        {
            if(onelineString[n].length()<=0)break;
            buf[n]=onelineString[n].split(",",maxwidthn);
        }
        return n;
    }
    public static String[] GetPrintFormatList() {
        return _GetPrintFormatList(GetsingleweightFormatdir());
    }
    public static String[] GetMaddPrintFormatList() {
        return  _GetPrintFormatList(GetmaddweightFormatdir());
    }
    public static String[] _GetPrintFormatList(String dir) {
        String PfStrings[],stemp;
        File f = new File(dir);
        if (!f.exists()) {
            f.mkdirs();
        }
        File[] files = f.listFiles();

        List<String> items = new ArrayList<String>();
        for (int i = 0;i < files.length; i++) {
            if(files[i].isFile()){
                File file = files[i];
                stemp=PubFunction.getSuffix(file.getName()).toUpperCase(Locale.ENGLISH);
                if("BIN".equals(stemp)||"TXT".equals(stemp))items.add(file.getName());
            }
        }
        PfStrings=items.toArray(new String[items.size()]);
        return PfStrings;
    }
    public static String GetsingleweightFormatdir()
    {
        return BaseSaveDir+"/printformat/singleweight";

    }
    public static String GetmaddweightFormatdir()
    {
        return BaseSaveDir+"/printformat/maddweight";

    }



    /**
     * 判断是否开启了自动亮度调节
     *
     * @param
     * @return
     */
    public static boolean isAutoBrightness(ContentResolver aContentResolver) {
        boolean automicBrightness = false;
        try {
            automicBrightness = Settings.System.getInt(aContentResolver,
                    Settings.System.SCREEN_BRIGHTNESS_MODE) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
        } catch (SettingNotFoundException e) {
            e.printStackTrace();
        }
        return automicBrightness;
    }
    /**
     * 获取屏幕的亮度
     *
     * @param activity
     * @return
     */
    public static int getScreenBrightness(Activity activity) {
        int nowBrightnessValue = 0;
        ContentResolver resolver = activity.getContentResolver();
        try {
            nowBrightnessValue = Settings.System.getInt(
                    resolver, Settings.System.SCREEN_BRIGHTNESS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return nowBrightnessValue;
    }
    /**
     * 设置亮度
     *
     * @param activity
     * @param brightness
     */
    public static void setBrightness(Activity activity, int brightness) {
        // Settings.System.putInt(activity.getContentResolver(),
        // Settings.System.SCREEN_BRIGHTNESS_MODE,
        // Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.screenBrightness = Float.valueOf(brightness) * (1f / 255f);
        activity.getWindow().setAttributes(lp);

    }

    /**
     * 停止自动亮度调节
     *
     * @param activity
     */
    public static void stopAutoBrightness(Activity activity) {
        Settings.System.putInt(activity.getContentResolver(),
                Settings.System.SCREEN_BRIGHTNESS_MODE,
                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
    }

    /**
     * 开启亮度自动调节
     *
     * @param activity
     */
    public static void startAutoBrightness(Activity activity) {
        Settings.System.putInt(activity.getContentResolver(),
                Settings.System.SCREEN_BRIGHTNESS_MODE,
                Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
    }


    @SuppressLint("NewApi")
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat) {
            if(DocumentsContract.isDocumentUri(context, uri))
            {
                // ExternalStorageProvider
                if (isExternalStorageDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];

                    if ("primary".equalsIgnoreCase(type)) {
                        return Environment.getExternalStorageDirectory() + "/" + split[1];
                    }

                    // TODO handle non-primary volumes
                }
                // DownloadsProvider
                else if (isDownloadsDocument(uri)) {

                    final String id = DocumentsContract.getDocumentId(uri);
                    final Uri contentUri = ContentUris.withAppendedId(
                            Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                    return getDataColumn(context, contentUri, null, null);
                }
                // MediaProvider
                else if (isMediaDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];

                    Uri contentUri = null;
                    if ("image".equals(type)) {
                        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if ("video".equals(type)) {
                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("audio".equals(type)) {
                        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }

                    final String selection = "_id=?";
                    final String[] selectionArgs = new String[] {
                            split[1]
                    };

                    return getDataColumn(context, contentUri, selection, selectionArgs);
                }
            }
            else {
                String[] filePathColumn = { MediaStore.Images.Media.DATA };
                Cursor cursor = context.getContentResolver().query(uri,filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String picturePath = cursor.getString(columnIndex);
                cursor.close();
                return picturePath;
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri The Uri to query.
     * @param selection (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
    // Storage Permissions
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    /**
     * Checks if the app has permission to write to device storage
     * If the app does not has permission then the user will be prompted to
     * grant permissions
     *
     * @param activity
     */
    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            int permission = activity.checkSelfPermission(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);

            if (permission != PackageManager.PERMISSION_GRANTED) {
                // We don't have permission so prompt the user
                activity.requestPermissions( PERMISSIONS_STORAGE,
                        REQUEST_EXTERNAL_STORAGE);
            }
        }
    }
    public static  boolean isTouchPointInView(View view, int x, int y) {
        if (view == null) {
            return false;
        }
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        int left = location[0];
        int top = location[1];
        int right = left + view.getWidth();
        int bottom = top + view.getHeight();
        //view.isClickable() &&
        if (y >= top && y <= bottom && x >= left
                && x <= right) {
            return true;
        }
        return false;
    }

    public static class ExBordMsg{
        public float BattleVolt;
        public boolean bCheckPort;
        public boolean bIsChargeing;
        public boolean bFinishedChargeing;
    }
}